package com.zbbt.sportslottery.ui.fragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.app.Constant;
import com.zbbt.sportslottery.app.ServerConfig;
import com.zbbt.sportslottery.bean.FindingNewsInformation;
import com.zbbt.sportslottery.bean.IndexFunBean;
import com.zbbt.sportslottery.bean.SuperResult;
import com.zbbt.sportslottery.bean.UserInfo;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.net.parser.Result;
import com.zbbt.sportslottery.net.parser.ResultParser;
import com.zbbt.sportslottery.ui.activity.ExchangeRecordActivity;
import com.zbbt.sportslottery.ui.activity.HDQListActivity;
import com.zbbt.sportslottery.ui.activity.LoginActivity;
import com.zbbt.sportslottery.ui.activity.SaoYiSaoActivity;
import com.zbbt.sportslottery.ui.activity.SettingsActicity;
import com.zbbt.sportslottery.ui.widget.CircleImageView;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.Md5;
import com.zbbt.sportslottery.util.SharePreferUtil;
import com.zbbt.sportslottery.util.ToastUtil;
import com.zbbt.sportslottery.util.UmengUtil;

/**
 * 
 * @ClassName: UserFragment
 * @Description: 用户中心
 * @author：GaomingShuo
 * @date：2015-3-3 上午10:36:02
 * @version V1.0
 */
public class UserFragment extends BaseMenuFragment {
	private LinearLayout tiyanquan_layout;
	private LinearLayout user_middle;
	private TextView user_name_tx;
	private TextView tiyanquan_num_tx;
	private TextView caidou_tx;
	private TextView confirmtext;
	private TextView recordtext;
	public static boolean refresh = false;
	private static CircleImageView iv_head;
	// 店主
	private LinearLayout shaoyisao_layout;
	private LinearLayout exchange_layout;
	private LinearLayout mLLcontent;
	private LayoutInflater inflater;
	/* 头像名称 */
	private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
	private static final String PHOTO_TEMP_SRC = "/sdcard/fjtc_photo_head.jpg";
	private Bitmap bitmap;
	private File tempFile;
	private LinearLayout user_top;
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private Handler handler;
	private Toolbar toolbar;

	public UserFragment() {}

	public static UserFragment getInstance() {
		return new UserFragment();
	}

	/*
	 * 彩民的界面
	 */
	@Override
	protected void initView(LayoutInflater inflater) {
		this.inflater = inflater;
		mView = inflater.inflate(R.layout.fragment_me, null);
		mLLcontent = (LinearLayout) findViewById(R.id.content_me);
	}

	@Override
	protected void setListener() {}

	@Override
	protected void initData() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.INTENT_ACTION_LOGIN_SUCCESS);
		filter.addAction(Constant.INTENT_ACTION_CHANGE_LOGIN);
		context.registerReceiver(broadcastReceiver, filter);
	};

	@Override
	protected void onClickEvent(View v) {
		switch (v.getId()) {
		case R.id.tv_right:// 设置界面
			SettingsActicity.setHandler(handler);
			Intent intent = new Intent(context, SettingsActicity.class);
			startActivity(intent);

			break;
		case R.id.tiyanquan_layout:// 体验券
			if (!App.isLogin) {
				goActivity(LoginActivity.class);
			} else {
				UmengUtil.onEvent(context, Constant.UMENG_TIYANQUAN);
				goActivity(HDQListActivity.class);
			}
			break;
		case R.id.user_middle:
			if (!App.isLogin) {
				goActivity(LoginActivity.class);
			} else {
				UmengUtil.onEvent(context, Constant.UMENG_CAIDOU_RECODE);
				ToastUtil.showLong("暂无记录");
			}

			break;
		case R.id.user_top:
			if (!App.isLogin) {
				goActivity(LoginActivity.class);
			}
			break;
		case R.id.my_head:
			UmengUtil.onEvent(context, Constant.UMENG_OWN_HEAD);
			final CharSequence[] charSequences = { "从相册选择", "从手机拍照" };
			AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
			builder.setTitle("选择").setItems(charSequences, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (which == 0) {
						gallery();
					} else {
						camera();
					}
				}
			}).show();
			break;
		case R.id.shaoyisao_layout:
			if (!App.isLogin) {
				goActivity(LoginActivity.class);
			} else {
				goActivity(SaoYiSaoActivity.class);
			}

			break;
		case R.id.exchange_layout:
			if (!App.isLogin) {
				goActivity(LoginActivity.class);
			} else {
				goActivity(ExchangeRecordActivity.class);
			}
			break;
		case R.id.user_name_tx:
			if (!App.isLogin) {
				goActivity(LoginActivity.class);
			}
			break;
		case R.id.shop_head:
			if (App.isLogin) {
				UmengUtil.onEvent(context, Constant.UMENG_OWN_HEAD);
				final CharSequence[] charSequence = { "从相册选择", "从手机拍照" };
				AlertDialog.Builder builders = new AlertDialog.Builder(this.getActivity());
				builders.setTitle("选择").setItems(charSequence, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (which == 0) {
							gallery();
						} else {
							camera();
						}
					}
				}).show();
				break;
			}
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		String userType = SharePreferUtil.getString(Constant.USER_TYPE, "");
		if (userType.equals("1")) {
			// 店主
			initViewShopOwner();
		} else {
			// 彩民
			initViewUesr();
		}
		if (!App.isLogin) {
			String userName = SharePreferUtil.getString(Constant.USER_NAME, "");
			String password = SharePreferUtil.getString(Constant.PASSWORD, "");
			user_name_tx.setText("点击登录");
			if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password)) {
				user_name_tx.setText("自动登录中");
				httpData(userName, password);
			}
			user_top.setOnClickListener(this);
			iv_head.setOnClickListener(null);
		}
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == Constant.INTENT_LOGIN) {
					iv_head.invalidate();
					iv_head.postInvalidate();
					iv_head.setImageDrawable(context.getResources().getDrawable(R.drawable.left_menu_head));
					user_name_tx.setText("");
				}
			}
		};

	}

	// 彩民
	private void initViewUesr() {
		mLLcontent.removeAllViews();
		View view = (LinearLayout) inflater.inflate(R.layout.fragment_user, (ViewGroup) mView, false);
		mLLcontent.addView(view);
		user_top = (LinearLayout) findViewById(R.id.user_top);
		tiyanquan_layout = (LinearLayout) findViewById(R.id.tiyanquan_layout);// 体验券的Linear
		tiyanquan_num_tx = (TextView) findViewById(R.id.tiyanquan_num_tx);// 体验券个数
		user_middle = (LinearLayout) findViewById(R.id.user_middle);// 彩豆的Linear
		caidou_tx = (TextView) findViewById(R.id.caidou_tx);// 彩豆的个数
		user_name_tx = (TextView) findViewById(R.id.user_name_tx);// 用户名
		iv_head = (CircleImageView) findViewById(R.id.my_head);// 头像
		tv_right = (TextView) findViewById(R.id.tv_right);
		setListenerUser();
		String usertop = SharePreferUtil.getString(Constant.USER_PHOTO_IMG, "");
		String username = SharePreferUtil.getString(Constant.USER_NAME, "");
		if (!TextUtils.isEmpty(username)) {
			user_name_tx.setText(username);
		}
		if (!TextUtils.isEmpty(usertop)) {
			setImageHead(usertop, iv_head);
		}
	}

	// 用户
	private void setListenerUser() {
		user_middle.setOnClickListener(this);
		tiyanquan_layout.setOnClickListener(this);
		user_top.setOnClickListener(this);
		iv_head.setOnClickListener(this);
		tv_right.setOnClickListener(this);
	}

	// 店主
	private void setListenerShopOwner() {
		user_top.setOnClickListener(this);
		shaoyisao_layout.setOnClickListener(this);
		exchange_layout.setOnClickListener(this);
		iv_head.setOnClickListener(this);
		tv_right.setOnClickListener(this);
	}

	// 店主
	private void initViewShopOwner() {
		mLLcontent.removeAllViews();
		View view = (LinearLayout) inflater.inflate(R.layout.fragment_shop_owener, (ViewGroup) mView, false);
		mLLcontent.addView(view);
		shaoyisao_layout = (LinearLayout) findViewById(R.id.shaoyisao_layout);
		exchange_layout = (LinearLayout) findViewById(R.id.exchange_layout);
		iv_head = (CircleImageView) findViewById(R.id.shop_head);
		user_name_tx = (TextView) findViewById(R.id.user_name_tx);
		user_top = (LinearLayout) findViewById(R.id.user_top);
		tv_right = (TextView) findViewById(R.id.tv_right);
		setListenerShopOwner();
		String usertop = SharePreferUtil.getString(Constant.USER_PHOTO_IMG, "");
		String username = SharePreferUtil.getString(Constant.USER_NAME, "");
		if (!TextUtils.isEmpty(username)) {
			user_name_tx.setText(username);
		}
		if (!TextUtils.isEmpty(usertop)) {
			setImageHead(usertop, iv_head);
		}
	}

	public String getCaiDou(String numstr) {
		try {
			long num = Long.parseLong(numstr);
			if (num > 99999) {
				return num / 10000 + "万";
			}
		} catch (Exception e) {
		}
		return numstr;
	}

	/*
	 * 从相册获取
	 */
	public void gallery() {
		// 激活系统图库，选择一张图片
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("image/*");
		startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (data != null && data.getData() != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				crop(uri);
			}

		} else if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
				Bitmap imageBitmap = BitmapFactory.decodeFile(tempFile.getAbsolutePath());
				if (imageBitmap != null) {
					crop(Uri.fromFile(tempFile));
				}
			} else {
				ToastUtil.showLong("未找到存储卡，无法存储照片！");
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			try {
				bitmap = data.getParcelableExtra("data");
				if (bitmap != null) {
					iv_head.setImageBitmap(bitmap);
					saveBitmap2file(bitmap, PHOTO_TEMP_SRC);
					postImgFile(PHOTO_TEMP_SRC);
					tempFile.delete();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	static boolean saveBitmap2file(Bitmap bmp, String filename) {
		CompressFormat format = Bitmap.CompressFormat.JPEG;
		int quality = 100;
		OutputStream stream = null;
		try {
			stream = new FileOutputStream(filename);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bmp.compress(format, quality, stream);
	}

	/*
	 * 从相机获取
	 */
	public void camera() {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		// 判断存储卡是否可以用，可用进行存储
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
		}
		startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
	}

	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	public static void postImgFile(final String string) {
		RequestParams params = new RequestParams();
		params.addQueryStringParameter("mobile", SharePreferUtil.getString(Constant.USER_NAME, ""));
		ZbHttpClient.postImg(ServerConfig.API_PHOTO_CHANGE, string, params, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				try {
					String jsonString = responseInfo.result;
					File file = new File(string);
					file.delete();
					final Object jsonResponse = parseResponse(jsonString);
					if (jsonResponse instanceof JSONObject) {
						JSONObject resultJson = (JSONObject) jsonResponse;
						try {
							Result mResult = ResultParser.parse(resultJson);
							SharePreferUtil.putString(Constant.USER_PHOTO_IMG, mResult.getResult() + "");
							ImageLoader.getInstance().displayImage(mResult.getResult(), iv_head, App.option,
									new ImageLoadingListener() {

										@Override
										public void onLoadingStarted(String imageUri, View view) {
											// TODO Auto-generated method stub

										}

										@Override
										public void onLoadingFailed(String imageUri, View view,
												FailReason failReason) {
											// TODO Auto-generated method stub
											((CircleImageView) view)
													.setImageResource(R.drawable.left_menu_head);
										}

										@Override
										public void onLoadingComplete(String imageUri, View view,
												Bitmap loadedImage) {
											// TODO Auto-generated method stub

										}

										@Override
										public void onLoadingCancelled(String imageUri, View view) {
											// TODO Auto-generated method stub

										}
									});
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}

			}

			@Override
			public void onFailure(HttpException error, String msg) {
				// LogUtil.printD("DemoLog", msg.toString());
			}
		});

	}

	public static Object parseResponse(String jsonString) {
		Object result = null;
		if (jsonString != null) {
			jsonString = jsonString.trim();
			if (jsonString.startsWith("{")) {
				try {
					result = new JSONTokener(jsonString).nextValue();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		if (result == null) {
			result = jsonString;
		}
		return result;
	}

	/**
	 * 自动登录
	 * 
	 * @param usernameContent
	 * @param passwordContent
	 */
	private void httpData(final String usernameContent, final String passwordContent) {
		JsonObject jsonObject = new JsonObject();
		jsonObject.addProperty("mobile", usernameContent);
		jsonObject.addProperty("password", Md5.getMD5(passwordContent));
		jsonObject.addProperty("loginType", "1");
		jsonObject.addProperty("firstLoginAppid", App.PARAM_APPID);
		ZbHttpClient.postNewApi(ServerConfig.API_LOGIN, jsonObject, new TypeGsonHttpHandler<UserInfo>(true) {

			@Override
			public void onSuccess(UserInfo data) {
				if (data != null) {
					// 登录成功，保存的数据
					SharePreferUtil.putString(Constant.USER_NAME, usernameContent);
					SharePreferUtil.putString(Constant.PASSWORD, passwordContent);
					SharePreferUtil.putString(Constant.USER_ID, data.getUserId());
					SharePreferUtil.putString(Constant.USER_TYPE, data.getUserType() + "");
					SharePreferUtil.putString(Constant.USER_SCORE, data.getTotalSource() + "");
					SharePreferUtil.putString(Constant.USER_PHOTO_IMG, data.getAvatar() + "");
					Intent loginSuccess = new Intent(Constant.INTENT_ACTION_LOGIN_SUCCESS);
					getActivity().sendBroadcast(loginSuccess);// 发广播
				}
			}

			@Override
			public void onFailure(String errorCode, String errorMsg) {
				user_name_tx.setText("未登录");
			}
		});
	}

	/**
	 * 接收登陆，注册的广播
	 */
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (Constant.INTENT_ACTION_LOGIN_SUCCESS.equals(intent.getAction())) {
				setUserInfo();
			} else if (Constant.INTENT_ACTION_CHANGE_LOGIN.equals(intent.getAction())) {

			}

		}

	};

	// 登陆成功后调用
	protected void setUserInfo() {
		// TODO Auto-generated method stub
		App.isLogin = true;
		user_name_tx.setText(SharePreferUtil.getString(Constant.USER_NAME, ""));
		String usertype = SharePreferUtil.getString(Constant.USER_TYPE, "");
		// if (usertype.equals("2")) {
		// String caidou = SharePreferUtil.getString(Constant.USER_SCORE, "");
		// if (!TextUtils.isEmpty(caidou)) {
		// caidou_tx.setText(getCaiDou(caidou));
		// }
		// tiyanquan_num_tx.setText(SharePreferUtil.getString(Constant.USER_COUPON_COUNT,
		// "0"));
		// }
		ImageLoader.getInstance().displayImage(SharePreferUtil.getString(Constant.USER_PHOTO_IMG, "0"),
				iv_head, App.option, new ImageLoadingListener() {
					@Override
					public void onLoadingStarted(String imageUri, View view) {}

					@Override
					public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
						((CircleImageView) view).setImageResource(R.drawable.left_menu_head);
					}

					@Override
					public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {}

					@Override
					public void onLoadingCancelled(String imageUri, View view) {}
				});
		iv_head.setOnClickListener(this);
		ToastUtil.showShort("登录成功");
	}

	private void setImageHead(String usertop, CircleImageView head) {
		ImageLoader.getInstance().displayImage(usertop, head, App.option, new ImageLoadingListener() {
			@Override
			public void onLoadingStarted(String imageUri, View view) {

			}

			@Override
			public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
				((CircleImageView) view).setImageResource(R.drawable.left_menu_head);
			}

			@Override
			public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

			}

			@Override
			public void onLoadingCancelled(String imageUri, View view) {

			}
		});
	}
}
